<?php
/**
 * Created by PhpStorm.
 *Author:huminghui
 * User: Administrator
 * Date: 2020/4/17
 * Time: 17:52
 */

namespace app\admin\model;


use think\helper\hash\Md5;
use think\Model;

class User extends Model
{
    /*
     * 登录
     */
    public function login($data){
       $user= $this->where("username",$data['username'])->find();
       if($user){
           header("Cache-control: private");
           if($user['password']==md5($data['password'])){
               session("username",$user['username']);
               session("uid",$user['id']);

               return 3;//登录成功
           }else{
               return 2;//密码错误
           }
       }else{
           return 1;//用户不存在
       }
    }
    /*
   * 保存数据
   */
    public function saveData($data){
        $userData=array();
        $groupAccess=array();
        $userData['create_time']=date('Y-m-d H:i:s',time());
        $userData['username']=$data['username'];
        $userData['password']=md5( $data['password']);
        if($this->save($userData)){
            $groupAccess['uid']=$this->id;
            $groupAccess['group_id']=$data['group_id'];
            db('auth_group_access')->insert($groupAccess);
            return true;
        }else{
            return false;
        }
    }
    /*
  * 更新数据
  */
    public function updateData($data){
        $userData=array();
        $userData['update_time']=date('Y-m-d H:i:s',time());
        $userData['id']=$data['id'];
        $userData['username']=$data['username'];
        $userData['password']=md5( $data['password']);
        if($this->update($userData)){
            db('auth_group_access')->where('uid',$data['id'])->update(['group_id' => $data['group_id']]);
            return true;
        }else{
            return false;
        }
    }
    /*
    * 读取所有数据
    */
    public function readAllData(){
        return $this->select()->toArray();
    }
    /*
 * 根据id查询数据
 */
    public function readDataById($data){
        return $this->where($data)->find()->toArray();
    }
    /*
   * 根据id删除数据
   */
    public function delDataById($data){
        if($this->where($data)->delete()){
            db("auth_group_access")->where("uid",$data['id'])->delete();
            return true;
        }else{
            return false;
        }
    }
}